package com.comsoftstar.nt5s.Activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hzc.imagepicker.SImagePicker;
import com.hzc.imagepicker.activity.PhotoPickerActivity;
import com.hzc.nt5s.IConstant;
import com.hzc.nt5s.R;
import com.hzc.nt5s.adapter.PickAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2017/8/22 质量评议--直接评议
 */


public class QualityDirectAppraisalActivity extends AppCompatActivity implements View.OnClickListener {


    public static final int REQUEST_CODE_IMAGE = 101;
    private JSONArray organization;
    private List<String> list_group;
    private Map<String, String> map;
    private String[] strs_group;
    private JSONArray standard;
    private List<String> list_standard;
    private Map<String, String> standardmap;
    private String[] strs_standard;
    private StringBuffer group = new StringBuffer(1000);
    private TextView tv_workgroup, tv_regulations;
    private GridView gridView;
    private Button upload, tv_back, tv_save;
    private List<String> url = new ArrayList<>();
    private List<String> pickedlist = new ArrayList<>();
    private boolean isShowDelete = false;
    private PickAdapter pickAdapter;
    private TextView tv_standard, tv_cardNum;
    private RelativeLayout rl_workshop, rl_workshop_1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quality_direct_appraisal);
        initView();
        initData();
    }


    private void initView() {
        list_group = new ArrayList<>();
        list_standard = new ArrayList<>();
        map = new HashMap<>();
        standardmap = new HashMap<>();

        tv_workgroup = (TextView) findViewById(R.id.tv_group_quality);
        tv_regulations = (TextView) findViewById(R.id.tv_regulations);
        rl_workshop = (RelativeLayout) findViewById(R.id.rl_workshop);
        rl_workshop_1 = (RelativeLayout) findViewById(R.id.rl_workshop_1);

        tv_back = (Button) findViewById(R.id.tv_back_quality);
        tv_save = (Button) findViewById(R.id.tv_save_quality);
        upload = (Button) findViewById(R.id.btn_upload_quality);
        pickAdapter = new PickAdapter(QualityDirectAppraisalActivity.this);
        gridView = (GridView) findViewById(R.id.view_pic);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                seeBig(url, i);
            }
        });
        tv_standard = (TextView) findViewById(R.id.textView0);
        tv_cardNum = (TextView) findViewById(R.id.textView1);

    }

    private void initData() {

        getQualityOrganization();

        tv_workgroup.setOnClickListener(this);
        tv_regulations.setOnClickListener(this);
        rl_workshop.setOnClickListener(this);
        rl_workshop_1.setOnClickListener(this);

        tv_back.setOnClickListener(this);
        tv_save.setOnClickListener(this);
        upload.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back_quality:
                finish();
                break;
            case R.id.tv_save_quality:

//                    SaveDialog();

                break;
            case R.id.btn_upload_quality:
                SImagePicker
                        .from(QualityDirectAppraisalActivity.this)
                        .maxCount(9)
                        .rowCount(3)
                        .showCamera(true)
                        .pickMode(SImagePicker.MODE_IMAGE)
                        .forResult(REQUEST_CODE_IMAGE);
            case R.id.rl_workshop:
            case R.id.tv_group_quality:
                showWorkShopDialog();
                break;
            case R.id.rl_workshop_1:
            case R.id.tv_regulations:

                Intent intent = new Intent(QualityDirectAppraisalActivity.this, QualityRegulationsActivity.class);
                startActivity(intent);

                break;


        }
    }

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }

        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    private void showWorkShopDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("车间组别");
        group.delete(0, group.length());

        builder.setMultiChoiceItems(strs_group, null, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {

                if (isChecked) {
                    group.append(strs_group[which] + ",");
                }

            }

        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tv_workgroup.setText(group.deleteCharAt(group.length() - 1).toString());
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }

    private void getQualityOrganization() {
        RequestParams params = new RequestParams(IConstant.URL + "getOrganization");
        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                System.out.println("返回结果：" + result);
                try {
                    organization = new JSONArray(result);
                    for (int i = 0; i < organization.length(); i++) {
                        JSONObject jo = (JSONObject) organization.get(i);
                        list_group.add(jo.optString("DeptName"));
                        map.put(jo.optString("DeptName"), jo.optString("DeptNo"));
                    }
                    strs_group = (String[]) list_group.toArray(new String[0]);
                    System.out.println("部门名称" + strs_group);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void delete(int position) {//删除选中项方法
        List<String> newList = new ArrayList<String>();
        if (isShowDelete) {
            pickedlist.remove(position);
        }
        newList.addAll(pickedlist);
        pickedlist.clear();
        pickedlist.addAll(newList);
        url.clear();
        url.addAll(newList);
    }

    public void seeBig(List<String> url, int position) {
        Intent intent = new Intent();
        intent.setClass(QualityDirectAppraisalActivity.this, BigImgActivity.class);
        intent.putExtra("url", url.get(position).toString());
        startActivity(intent);
    }


//
//    private void SaveDialog() {
//
//        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);  //先得到构造器
//        builder.setTitle("提示"); //设置标题
//        builder.setMessage("确定要保存？"); //设置内容
//        builder.setIcon(R.mipmap.ic_launcher);//设置图标，图片id即可
//        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //设置确定按钮
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss(); //关闭dialog
//
//                RequestParams params = new RequestParams(IConstant.URL + "qualityReview");
//                User user = PreferencesUtil.getUser(QualityDirectAppraisalActivity.this);
//                params.addBodyParameter("UserName", user.getUserName());//文件后缀名(带点)
//                params.addBodyParameter("CardNum", et_cardNum.getText().toString());
//                params.addBodyParameter("SimpleRegulation", et_standard.getText().toString());
//                map.put("请选择车间", "");
////                  params.addBodyParameter("groupName",tv_workgroup.getText().toString());
//
//                StringBuffer stringBuffer = new StringBuffer(1000);
//
//                for (int i = 0; i < tv_workgroup.getText().toString().split(",").length; i++) {
//                    stringBuffer.append(map.get(tv_workgroup.getText().toString().split(",")[i]) + ",");
//                }
//                stringBuffer.deleteCharAt(stringBuffer.length() - 1);
//                params.addBodyParameter("WorkShop", stringBuffer.toString());
//                if (pickedlist != null && !pickedlist.isEmpty()) {
//                    List<KeyValue> list = new ArrayList<>();
//                    for (int i = 0; i < pickedlist.size(); i++) {
//                        list.add(new KeyValue("image" + i, new File(pickedlist.get(i))));
//                        MultipartBody body = new MultipartBody(list, "UTF-8");
//                        params.setRequestBody(body);
//                    }
//                }
//                System.out.println("请求的URL：" + params.toString());
//                x.http().post(params, new Callback.CommonCallback<String>() {
//                    @Override
//                    public void onSuccess(String result) {
//                        System.out.println(result);
//                        Toast.makeText(QualityDirectAppraisalActivity.this, "保存成功", Toast.LENGTH_LONG).show();
//                        finish();
//                    }
//
//                    @Override
//                    public void onError(Throwable ex, boolean isOnCallback) {
//                        System.out.println(ex);
//                    }
//
//                    @Override
//                    public void onCancelled(CancelledException cex) {
//
//                    }
//
//                    @Override
//                    public void onFinished() {
//
//                    }
//                });
//
//
//            }
//        });
//        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//            }
//        });
//        //参数都设置完成了，创建并显示出来
//        builder.create().show();
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            final ArrayList<String> pathList =
                    data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);
            System.out.println("pathList" + pathList.toString());
            pickedlist.addAll(pathList);
            url.addAll(pickedlist);
            pickAdapter = new PickAdapter(QualityDirectAppraisalActivity.this);
            pickAdapter.setNewData(pickedlist);
            gridView.setAdapter(pickAdapter);
            isShowDelete = false;
            pickAdapter.setIsShowDelete(isShowDelete);
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    seeBig(url, i);
                }
            });
            gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if (isShowDelete) {
                        isShowDelete = false;
                    } else {
                        isShowDelete = true;
                        pickAdapter.setIsShowDelete(isShowDelete);
                        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                                delete(position);//删除选中项
                                pickAdapter = new PickAdapter(QualityDirectAppraisalActivity.this);//重新绑定一次adapter
                                pickAdapter.setNewData(pickedlist);
                                pickAdapter.setIsShowDelete(isShowDelete);
                                gridView.setAdapter(pickAdapter);
                            }
                        });
                    }
                    pickAdapter.setIsShowDelete(isShowDelete);//setIsShowDelete()方法用于传递isShowDelete值
                    return true;
                }
            });

        }
    }
}
